#!/bin/bash
#
# Copyright (C) 2013-2021 Spring Studio
# Copyright (C) 2013-2021 Dou Dongchun <doudongchun@163.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

REMOTE_REPO=$1
LOCAL_WORKSPACE=$2

set -e

FILE=$(basename $REMOTE_REPO)

echo "========================================"
echo "[*] get $(basename $LOCAL_WORKSPACE)"
echo "========================================"

if [ -z "$REMOTE_REPO" ] || [ -z "$LOCAL_WORKSPACE" ]; then
  echo "invalid call wget-repo-base.sh '$REMOTE_REPO' '$LOCAL_WORKSPACE'"
elif [ ! -d "$LOCAL_WORKSPACE" ]; then
  wget -N $REMOTE_REPO
  # tar.bz2
  NAME="${FILE%%.tar.bz2}"
  if [ "$FILE" != "$NAME" ]; then
    tar -zxf $FILE
    if [ "$NAME" != "$LOCAL_WORKSPACE" ]; then
      mv -f "$NAME" "$LOCAL_WORKSPACE/"
    fi
    exit 1
  fi
  # tar.gz 
  NAME="${FILE%%.tar.gz}"
  if [ "$FILE" != "$NAME" ]; then
    tar -zxf $FILE
    if [ "$NAME" != "$LOCAL_WORKSPACE" ]; then
      mv -f "$NAME/" "$LOCAL_WORKSPACE"
    fi
    exit 1
  fi
  # tar
  NAME="${FILE%%.tar}"
  if [ "$FILE" != "$NAME" ]; then
    tar -zxf $FILE
    if [ "$NAME" != "$LOCAL_WORKSPACE" ]; then
      mv -f "$NAME" "$LOCAL_WORKSPACE/"
    fi
    exit 1
  fi
  # zip
  NAME="${FILE%%.zip}"
  if [ "$FILE" != "$NAME" ]; then
    unzip $FILE
    if [ "$NAME" != "$LOCAL_WORKSPACE" ]; then
      mv -f "$NAME" "$LOCAL_WORKSPACE/"
    fi
    exit 1
  fi
  echo "UNKNOW FORMAT: $FILE"
  exit 0
else
  echo "The '$LOCAL_WORKSPACE' already exists."
fi
